package spring.distributed.lock.samples.controller;

import cn.fang2chen.distributed.lock.spring.TokenLeasingFactory;
import cn.fang2chen.java.distributed.lock.framework.RemoteLockParam;
import cn.fang2chen.java.distributed.lock.framework.impl.DistributedTokenLeasing;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * Title: TokenLeasingTestController
 *
 * @author dcmini chen
 * @since 1.0.0
 */
@RestController
@RequestMapping("/leasing")
@Slf4j
public class TokenLeasingTestController {

    @Autowired
    private TokenLeasingFactory tokenLeasingFactory;

    @RequestMapping(path = "/token", method = RequestMethod.GET)
    public String leasing(String tokenName, Long expire) {
        DistributedTokenLeasing distributedTokenLeasing = tokenLeasingFactory.tryGetIfNullCreate(new RemoteLockParam(tokenName, "", 50000));
        if (distributedTokenLeasing.tryGainToken(tokenName, expire)) {
            log.info("{} 获得  token [{}] 租借 {}", Thread.currentThread().getName(), tokenName, expire);
            return "success";
        } else {
            long l = distributedTokenLeasing.remainingLeaseTerm(tokenName);
            return "剩余租期" + l;
        }
    }

}
